import string
import string_operations as str_op
from document import *

TITLETAG = 'Title:'
AUTHORTAG = 'Author:'
RELEASETAG = 'Release'
STARTTAG = 'START OF TH'
SPLITTAG = '***'

def parseEbk(ebk_content, new_doc):
    """
    In ebooks, the content is separated from the header by the string
    *** START OF THIS PROJECT GUTENBERG EBOOK THE TIME MACHINE ***
    
    So when we split it by '***', then find the corresponding
    header and body (which starts with the STARTTAG). 
    
    Note: The header of the ebook is also parsed implicitly but is not returned 
    
    Return a list of parsed body of the ebook.  
    """
    header, body = getHeaderAndBody(ebk_content)
    if header=='':
        return body
    parseEbkHead(header, new_doc)
    return str_op.parseString(body)

def getHeaderAndBody(ebk_content):
    """
    Return the header and the body of the ebk_content
    """
    part_list = ebk_content.split(SPLITTAG)
    body_index = 0
    for index in range(0,len(part_list)-1):
        if part_list[index].startswith(' ' + STARTTAG) or part_list[index].startswith(STARTTAG):
            body_index = index+1
            break
    if body_index == 0: 
        printInvalidEbk()
        return '', ebk_content
    
    header=part_list[body_index-2]
    body = part_list[body_index]
    return header, body    

def parseEbkHead(header, new_doc):
    """
    Process the ebook headers, calls processTitle and processAuthor 
    methods 
    """
    header_list = makeHeaderList(header)
    processTitle(header_list,new_doc)
    processAuthor(header_list, new_doc)

def makeHeaderList(header):
    """
    Create a list of header delimited by spaces
    """
    return header.split()

def printInvalidEbk():
    """
    Print error that this is not a valid ebook
    """
    self.output("This is not a standard ebook file, entire file being indexed.")
    
def processTitle(header_list, new_doc):
    """
    Save the title of the ebk into the document's title attribute. 
    
    Note: new_doc's input_title, or unformatted title, also gets updated. 
    """
    title = ""
    title_begin = header_list.index(TITLETAG)
    author_begin = header_list.index(AUTHORTAG)
    for index in range((title_begin+1),(author_begin)):
        title += header_list[index] + " "
    new_doc.input_title = title
    new_doc.title = str_op.formatString(title)
    
def processAuthor(header_list, new_doc):
    author = ""
    author_begin = header_list.index(AUTHORTAG)
    author_end = header_list.index(RELEASETAG)    
    for index in range((author_begin+1),(author_end)):
        author += header_list[index] + " "
    new_doc.input_authors = author
    new_doc.authors = str_op.formatString(author)
